import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/pages/home/HomeContainer/index.vue'),
    redirect: '/home/joinMeeting',
    children: [
      {
        path: 'joinMeeting',
        name: 'joinMeeting',
        component: () => import('@/pages/home/JoinMeeting/index.vue')
      },
      {
        path: 'createMeeting',
        name: 'createMeeting',
        component: () => import('@/pages/home/CreateMeeting/index.vue')
      },
      {
        path: 'user/baseInfo',
        name: 'user/baseInfo',
        component: () => import('@/pages/user/BaseInfo/index.vue')
      },
      {
        path: 'user/updateAvatar',
        name: 'user/updateAvatar',
        component: () => import('@/pages/user/UpdateAvatar/index.vue')
      },
      {
        path: 'user/updateInfo',
        name: 'user/updateInfo',
        component: () => import('@/pages/user/UpdateInfo/index.vue')
      },
      {
        path: 'user/updatePassword',
        name: 'user/updatePassword',
        component: () => import('@/pages/user/UpdatePassword/index.vue')
      },
      {
        path: 'history/created',
        name: 'history/created',
        component: () => import('@/pages/history/Created/index.vue')
      },
      {
        path: 'history/join',
        name: 'history/join',
        component: () => import('@/pages/history/Join/index.vue')
      }
    ]
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/pages/auth/register/index.vue')
  },
  {
    path: '/meeting/:id',
    name: 'meeting',
    component: () => import('@/pages/meeting/MeetingContainer/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, _from, next) => {
  // 检查用户是否正在尝试访问注册页面
  if (to.name === 'register') {
    // 如果是，直接放行
    next()
  } else {
    // 检查本地存储中是否有 user 对象
    const user = localStorage.getItem('user')
    if (user) {
      // 解析本地存储中的 user 字符串
      const parsedUser = JSON.parse(user)
      // 检查解析后的 user 对象中是否有 token
      if (parsedUser && parsedUser.token) {
        // 如果有 token，放行
        next()
      } else {
        // 如果没有 token 或 user 对象不合法，重定向到注册页面
        ElMessage.warning('请登录')
        next({ name: 'register' })
      }
    } else {
      // 如果本地存储中没有 user 对象，重定向到注册页面
      ElMessage.warning('请登录')
      next({ name: 'register' })
    }
  }
})

export default router
